<?php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

$pageTitle = "分类管理";
include 'includes/header.php';
?>

<div class="container">
    <div class="page-header">
        <h1>分类管理</h1>
        <button class="btn btn-primary" onclick="showAddCategoryModal()">
            <i class="fas fa-plus"></i> 添加分类
        </button>
    </div>
    
    <div class="categories-container">
        <div id="categories-list" class="categories-grid">
            <!-- 分类列表将通过JavaScript动态加载 -->
        </div>
    </div>
</div>

<!-- 添加/编辑分类模态框 -->
<div id="categoryModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle">添加分类</h2>
            <span class="close" onclick="closeCategoryModal()">&times;</span>
        </div>
        <form id="categoryForm">
            <input type="hidden" id="categoryId" name="category_id">
            <div class="form-group">
                <label for="categoryName">分类名称</label>
                <input type="text" id="categoryName" name="name" placeholder="请输入分类名称" required>
            </div>
            <div class="form-group">
                <label for="categoryDescription">分类描述</label>
                <textarea id="categoryDescription" name="description" placeholder="请输入分类描述" rows="3"></textarea>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-accent" onclick="closeCategoryModal()">取消</button>
            </div>
        </form>
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="deleteModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>确认删除</h2>
            <span class="close" onclick="closeDeleteModal()">&times;</span>
        </div>
        <div class="modal-body">
            <p>确定要删除分类 "<span id="deleteCategoryName"></span>" 吗？</p>
            <p class="warning">删除后，该分类下的文章将不再关联此分类。</p>
        </div>
        <div class="form-actions">
            <button class="btn btn-danger" onclick="confirmDelete()">确认删除</button>
            <button class="btn btn-accent" onclick="closeDeleteModal()">取消</button>
        </div>
    </div>
</div>

<script>
let categories = [];
let deleteCategoryId = null;

// 页面加载时获取分类列表
document.addEventListener('DOMContentLoaded', function() {
    loadCategories();
});

// 加载分类列表
function loadCategories() {
    fetch('api.php?action=get_categories')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                categories = data.data;
                renderCategories();
            } else {
                alert('加载分类失败：' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('加载分类失败，请重试');
        });
}

// 渲染分类列表
function renderCategories() {
    const container = document.getElementById('categories-list');
    
    if (categories.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-tags"></i>
                <h3>暂无分类</h3>
                <p>创建第一个分类来组织你的文章吧！</p>
                <button class="btn btn-primary" onclick="showAddCategoryModal()">创建分类</button>
            </div>
        `;
        return;
    }
    
    container.innerHTML = categories.map(category => `
        <div class="category-card">
            <div class="category-content">
                <h3>${category.name}</h3>
                <p>${category.description || '暂无描述'}</p>
            </div>
            <div class="category-actions">
                <button class="btn btn-small btn-accent" onclick="editCategory(${category.category_id})">
                    <i class="fas fa-edit"></i> 编辑
                </button>
                <button class="btn btn-small btn-danger" onclick="showDeleteModal(${category.category_id}, '${category.name}')">
                    <i class="fas fa-trash"></i> 删除
                </button>
            </div>
        </div>
    `).join('');
}

// 显示添加分类模态框
function showAddCategoryModal() {
    document.getElementById('modalTitle').textContent = '添加分类';
    document.getElementById('categoryForm').reset();
    document.getElementById('categoryId').value = '';
    document.getElementById('categoryModal').style.display = 'block';
}

// 显示编辑分类模态框
function editCategory(categoryId) {
    const category = categories.find(c => c.category_id == categoryId);
    if (!category) return;
    
    document.getElementById('modalTitle').textContent = '编辑分类';
    document.getElementById('categoryId').value = category.category_id;
    document.getElementById('categoryName').value = category.name;
    document.getElementById('categoryDescription').value = category.description || '';
    document.getElementById('categoryModal').style.display = 'block';
}

// 关闭分类模态框
function closeCategoryModal() {
    document.getElementById('categoryModal').style.display = 'none';
}

// 显示删除确认模态框
function showDeleteModal(categoryId, categoryName) {
    deleteCategoryId = categoryId;
    document.getElementById('deleteCategoryName').textContent = categoryName;
    document.getElementById('deleteModal').style.display = 'block';
}

// 关闭删除模态框
function closeDeleteModal() {
    document.getElementById('deleteModal').style.display = 'none';
    deleteCategoryId = null;
}

// 确认删除
function confirmDelete() {
    if (!deleteCategoryId) return;
    
    const formData = new FormData();
    formData.append('action', 'delete_category');
    formData.append('category_id', deleteCategoryId);
    
    fetch('api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            closeDeleteModal();
            loadCategories();
        } else {
            alert(data.error || '删除失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('删除失败，请重试');
    });
}

// 处理分类表单提交
document.getElementById('categoryForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const categoryId = document.getElementById('categoryId').value;
    const name = document.getElementById('categoryName').value.trim();
    const description = document.getElementById('categoryDescription').value.trim();
    
    if (!name) {
        alert('分类名称不能为空');
        return;
    }
    
    const formData = new FormData();
    formData.append('action', categoryId ? 'update_category' : 'create_category');
    if (categoryId) {
        formData.append('category_id', categoryId);
    }
    formData.append('name', name);
    formData.append('description', description);
    
    fetch('api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            closeCategoryModal();
            loadCategories();
        } else {
            alert(data.error || '操作失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('操作失败，请重试');
    });
});

// 点击模态框外部关闭
window.onclick = function(event) {
    const categoryModal = document.getElementById('categoryModal');
    const deleteModal = document.getElementById('deleteModal');
    
    if (event.target === categoryModal) {
        closeCategoryModal();
    }
    if (event.target === deleteModal) {
        closeDeleteModal();
    }
}
</script>

<?php include 'includes/footer.php'; ?> 